import 'package:flutter/material.dart';
import 'package:flutterapp/api.dart';
import 'package:flutterapp/model/Result.dart';
import 'package:flutterapp/model/page.dart';
import 'package:flutterapp/model/productList.dart';
import 'package:flutterapp/model/productType.dart';
import 'package:flutterapp/model/productTypeList.dart';

/**
 * 注释：不能在获取数据前，setState,(要放在获取数据后！！！)
 */
class IndexScreen extends StatefulWidget{
  @override
  _IndexState createState() => _IndexState();
}

class _IndexState extends State<IndexScreen> with SingleTickerProviderStateMixin{

  List<ProductType> productTypeList = <ProductType>[];
  ProductType currentType = new ProductType();
  int currentIndex = null;
  int testIndex = 0;
//  Page page = new Page(page: 0,pageSize: 10);

  TabController tabController;


  void  fetchNetData() async {
    Result result = await apiGetProductTypeList();

    setState(() {
      productTypeList = new ProductTypeList.fromJson(result.data).productTypeList ;
      tabController = TabController(length: productTypeList.length, vsync: this);
      tabController.addListener(fetchProductListData);
//      currentType = productTypeList[0];
    });
    productTypeList.map((ProductType type) {
      type.productList = [];
      type.page = new Page(page: 0,pageSize: 15);
    }).toList();
    fetchProductListData();
    print('Howdy, ${result.data}!');
  }

  void fetchProductListData() async {
    if((currentIndex == tabController.index || (productTypeList[tabController.index].productList != null && productTypeList[tabController.index].productList.length > 0)) && productTypeList[tabController.index].page.page == 0) return;

//    if(currentType.id == type.id) return;
    Result result = await apiGetProductList(productTypeList[tabController.index]);

    setState(() {
      currentIndex = tabController.index;
      if(productTypeList[currentIndex].page.page == 0)currentType = productTypeList[currentIndex];
    });

    if(result != null && result.code == 0) {
      ProductList productList = new ProductList.fromJson(result.data);
      setState(() {
        productTypeList.map((ProductType productType) {
          if(productType.id == currentType.id) {
            productType.productList.addAll(productList.dataList);
            productType.page.page = productType.page.page+1;
            print("type is ${productType.optName} ,page  is ${productType.page.page}");
          }
        }).toList();
//        currentType.productList = productList.dataList;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    fetchNetData();
  }

  @override
  void dispose() {
    tabController?.dispose();
    super.dispose();
  }

  Widget _getListTile(type) {
    return new ListView.builder(
        itemCount:type.productList.length,
        semanticChildCount: 2,
        itemBuilder: (context,index) {
          print("当前index是 ${index}");
          if(index >= type.productList.length-1 ) {
            fetchProductListData();
          }
          return ListTile(
              title: Row(
                children: <Widget>[
                  Image.network(
                    type.productList[index].goodsThumbnailUrl,
                    height: 60,
                    width: 60,
                  ),
                  Container(
                    width: 250,
                    child: Text(
                      type.productList[index].goodsName,
                      softWrap:true,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                ],
              )
          );
        }
    );
  }

  @override
  Widget build(BuildContext context) {
    if (productTypeList.length == 0) {
      return new Scaffold(
        appBar: AppBar(title: Text("产品列表页")),
        body: Center(
          child: new CircularProgressIndicator(backgroundColor: Colors.green),
        ),
      );
    } else {
      return new MaterialApp(
        home:new Scaffold(
          appBar: AppBar(
//            leading: RaisedButton(
//                color: Colors.blue,
//                onPressed: () {
//                  Navigator.pop(context);
//                },
//                child: Icon(
//                  Icons.arrow_back,
//                  color: Colors.white,
//                ),
//            ),
//            title: Text("产品列表"),
            title: TabBar(
                isScrollable: true,
                controller: tabController,
                tabs: productTypeList.map<Widget>((ProductType type) {
                  return Tab(
                    text: type.optName,
                    icon: Icon(Icons.ac_unit),
                  );
                }).toList(),
            ),
          ),
          body: TabBarView(
              controller: tabController,
              children: productTypeList.map<Widget>((ProductType type) {
//                if(type.productList != null && type.productList.length > 0) {
                    return _getListTile(type);
//                }else {
//                  return ListView(
//                    children: <Widget>[
//                      new ListTile(
//                        leading: Icon(Icons.add),
//                        title: Text("测试"),
//                      ),
//                      new ListTile(
//                        leading: Icon(Icons.add),
//                        title: Text("测试"),
//                      ),
//                      new ListTile(
//                        leading: Icon(Icons.add),
//                        title: Text("测试"),
//                      ),
//                    ],
//                  );
//                }
              }).toList()
          ),
        )
      );
    }
  }
}
